var https = require('https');
var timeUtil = require('hy5b/time')
const querystring = require('querystring');
const t = require('hy5b/t')
var xlsx = require("node-xlsx");

// const datas = require('./data');
const datas = parseXls('./report.xls')

function parseXls(filepath) {
  var sheets = xlsx.parse(filepath);

  var table = sheets[0].data;
  var datas = []
  for (var i = 1; i < table.length; i++) {
    var row = table[i]
    var match = /([0-9]+)月([0-9]+)号/.exec(row[2])
    if (match) {
      var date = match[1] + ':' + match[2]
      var remark = row[3]
      var taskId = row[1]

      datas.push({ date, remark, taskId })
    }
  }
  return datas;
}

var options = {
  host: 'www.uyun.cn',
  port: 443,
  path: '/boss/opercentre/crm/task/insertLog',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    accept: 'application/json',
    cookie: 'erpsessionid=1b62b0be-596f-49a0-b1e5-ce639bcd1e25; bosstoken=9c0cdba5255d800cad44b9fd53f1ecf3a3552d5061abb1c69a2918a2211c1087'
  },
  rejectUnauthorized: false
};

function buildData(data) {
  return {
    // createTime: data.createTime,
    // engineerProject: data.engineerProject,
    lostTime: data.lostTime || 8,
    remark: data.remark || 'R13开发',
    taskId: data.taskId || '6c62090da66c4724bfa9a3752e09140b',
    taskType: data.taskType || '820d8d91c38542a88bb5bbd7a2527891'
  }
}

datas.forEach(function(data) {
  var date = data.date;

  var monthGroups = t.split(date, ';')

  var dates = [];

  monthGroups.forEach(function(monthGroup) {
    var monthSplit = t.split(monthGroup, ':')
    var month = monthSplit[0];
    var days = t.split(monthSplit[1], ',')
    days.forEach(function(day) {
      dates.push([month, day].join('/'));
    })
  })

  dates.forEach(function(date) {
    var postData = buildData(data);
    var localTimeString = '2018/' + date;
    postData.createTime  = timeUtil.localTimeString2millisecond(localTimeString);

    var postDataQueryString = querystring.stringify(postData)

    console.log(postData)

    var req = https.request(options, function(res) {
      console.log(`STATUS: ${res.statusCode}`);
      // console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      console.log(`TIME: ${localTimeString}`);
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
      });
      res.on('end', () => {
        console.log('--------------------------------------------------------------');
      });
    });
    req.on('error', (e) => {
      console.error(`problem with request: ${e.message}`);
    });

    // write data to request body
    req.write(postDataQueryString);
    req.end();
  })
})

